#include "MyFile.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


MyFile* Buy_MyFile()
{
    MyFile* fp = (MyFile*)malloc(sizeof(MyFile));
    fp->_fd = -1;
    fp->_flush_stauts = NONE_FLUSH;
    fp->_filename = NULL;
    fp->_mod = 0;
    fp->_truesize = 0;
    return fp;
}

int GetMod(const char* mod)
{
    int final_mod = 0;
    if(strcmp(mod, "w"))
    {
        // create + again
        final_mod = O_CREAT | O_TRUNC | O_WRONLY; 
    }
    else if(strcmp(mod, "a"))
    {
       // create + append
       final_mod = O_CREAT | O_APPEND | O_WRONLY;
    }
    else if(strcmp(mod, "r")){
       final_mod = O_RDONLY; 
    }
    else{
        // ...
    }
    return final_mod;
}

MyFile* Myfopen(const char* address, const char* mod)
{
    // 创建一个文件对象
    MyFile* fp = Buy_MyFile();
    fp->_filename = address;
    fp->_mod = GetMod(mod);
    fp->_fd = open(fp->_filename, fp->_mod, 0666);
    if(fp->_fd == -1)
    {
        perror("open fail!\n");
        exit(1);
    }
    fp->_flush_stauts = LINK_FLUSH;
    return fp;
}

int Myfwrite(const char* msg, int size, int num, MyFile* fp)
{
    while(num--)
        strncpy(fp->_buffer, msg, size);
    fp->_truesize += size;
   // 判断缓冲方式
   if(fp->_flush_stauts == NONE_FLUSH)
   {
        write(fp->_fd, fp->_buffer, fp->_truesize);
        fp->_truesize = 0;
        return 1;
   }
   else if(fp->_flush_stauts == LINK_FLUSH && fp->_buffer[size] == '\n')
   {
        write(fp->_fd, fp->_buffer, fp->_truesize);
        fp->_truesize = 0;
        return 1; 
   }
   else if(fp->_flush_stauts == FULL_FLUSH && fp->_truesize == BUFFER_SIZE)
   {
        write(fp->_fd, fp->_buffer, fp->_truesize);
        fp->_truesize = 0;
        return 1;
   }
   else{
       // ...
       return -1;
   }
   return -1;
}

void Myflush(MyFile* fp)
{ 
     write(fp->_fd, fp->_buffer, fp->_truesize);
     fp->_truesize = 0;
}

void Myfclose(MyFile* fp)
{
    close(fp->_fd);
    // 回收资源
    free(fp); 
}
